package taller.xml.parser;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

import taller.excepcion.ParserException;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.basic.DateConverter;

public class XStreamParser {

	private final String ENCODING = "UTF-8";
	private String defaultFormat = "yyyyMMdd";
	String[] acceptableFormats = new String[]{"dd-MM-yyyy","dd/MM/yyyy"};
	
	private OutputStream os = null;
	private OutputStreamWriter osw = null;
	private DateConverter dateConverter = null;
	private XStream xstream = null;
	
	public XStreamParser() throws ParserException{
	    try {
	    	this.os = new ByteArrayOutputStream();
	    	this.osw = new OutputStreamWriter(os, ENCODING);
	    	this.dateConverter = new DateConverter(defaultFormat, acceptableFormats );
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			throw new ParserException("Error al crear XStreamParser", e.getMessage());
		}
	}
	
	public XStream obtenerXStream(){
		xstream = new XStream();
	    xstream.autodetectAnnotations(true);
	    xstream.registerConverter(this.dateConverter);
	    
	    return xstream;
	}
	
	public void liberarXStream() throws ParserException{
		try {
			this.osw.close();
			this.os.close();
		} catch (IOException e) {
			e.printStackTrace();
			throw new ParserException("Error al liberar XStream", e.getMessage());
		}
	}
}